/*
 *
 *      Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: lengleng (wangiegie@gmail.com)
 *
 */

package com.pig4cloud.pigx.common.log.util;

import lombok.experimental.UtilityClass;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;

import java.lang.reflect.Method;

/**
 * 系统日志工具类
 */
@UtilityClass
public class UserLogUtils {

//	public UserLogs getUserLog() {
//		HttpServletRequest request = ((ServletRequestAttributes) Objects
//				.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
//		UserLogs userLogs = new UserLogs();
//		userLogs.setUid(Objects.requireNonNull(getUsername()));
//		userLogs.setLogType(LogTypeEnum.NORMAL.getType());
//		userLogs.setIp(ServletUtil.getClientIP(request));
//		userLogs.setRequestUri(URLUtil.getPath(request.getRequestURI()));
//		userLogs.setMethod(request.getMethod());
//		userLogs.setUserAgent(request.getHeader("user-agent"));
//		userLogs.setParams(HttpUtil.toParams(request.getParameterMap()));
//		userLogs.setCreateDate(LocalDateTime.now());
//		return userLogs;
//	}
//
//	public UserLogs getUserLog(HttpServletRequest request, String username) {
//
//		UserLogs userLogs = new UserLogs();
//		userLogs.setUid(username);
//		userLogs.setLogType(LogTypeEnum.NORMAL.getType());
//		userLogs.setIp(ServletUtil.getClientIP(request));
//		userLogs.setRequestUri(URLUtil.getPath(request.getRequestURI()));
//		userLogs.setMethod(request.getMethod());
//		userLogs.setUserAgent(request.getHeader("user-agent"));
//		userLogs.setParams(HttpUtil.toParams(request.getParameterMap()));
//		userLogs.setCreateDate(LocalDateTime.now());
//		return userLogs;
//	}

    /**
     * 获取客户端
     *
     * @return clientId
     */
    private String getClientId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication instanceof OAuth2Authentication) {
            OAuth2Authentication auth2Authentication = (OAuth2Authentication) authentication;
            return auth2Authentication.getOAuth2Request().getClientId();
        }
        return null;
    }

    /**
     * 获取用户名称
     *
     * @return username
     */
    private String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getName();
    }

    /**
     * 获取spel 定义的参数值
     *
     * @param context 参数容器
     * @param key     key
     * @param clazz   需要返回的类型
     * @param <T>     返回泛型
     * @return 参数值
     */
    public <T> T getValue(EvaluationContext context, String key, Class<T> clazz) {
        SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
        Expression expression = spelExpressionParser.parseExpression(key);
        return expression.getValue(context, clazz);
    }

    /**
     * 获取参数容器
     *
     * @param arguments       方法的参数列表
     * @param signatureMethod 被执行的方法体
     * @return 装载参数的容器
     */
    public EvaluationContext getContext(Object[] arguments, Method signatureMethod) {
        String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(signatureMethod);
        EvaluationContext context = new StandardEvaluationContext();
        if (parameterNames == null) {
            return context;
        }
        for (int i = 0; i < arguments.length; i++) {
            context.setVariable(parameterNames[i], arguments[i]);
        }
        return context;
    }

}
